package com.mjw.tender.feign.fallback;
import com.mjw.tender.dto.FileInfo;
import com.mjw.tender.dto.ResponseResult;
import com.mjw.tender.feign.UploadFeign;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.UUID;

/**
 * 文件上传熔断器
 * <p>
 * Description:
 * </p>
 */
@Component
public class UploadFeignFallback implements UploadFeign {

//    private static final String BREAKING_MESSAGE = "请求失败了，请检查您的网络";
    private String FILE_PAHT ="D:\\workspace\\myblogvue\\static\\img";

    @Override
    public ResponseResult upload(MultipartFile multipartFile) {

        String fileName = multipartFile.getOriginalFilename();
        String suffix = fileName.substring(fileName.lastIndexOf(".") + 1);
        String newName = UUID.randomUUID() + "." + suffix;

        File targetFile = new File(FILE_PAHT);
        if (!targetFile.exists()) {
            targetFile.mkdirs();
        }
        try {
            OutputStream out = new FileOutputStream(FILE_PAHT+newName);
            out.write(multipartFile.getBytes());
            FileInfo fileInfo = new FileInfo();
            fileInfo.setPath(FILE_PAHT+fileName);
            return new ResponseResult(ResponseResult.CodeStatus.OK,fileInfo);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            return new ResponseResult(ResponseResult.CodeStatus.FAIL);
        } catch (IOException e) {
            e.printStackTrace();
            return new ResponseResult(ResponseResult.CodeStatus.FAIL);
        }

    }
}
